// src/pages/RoleUserList/components/SelectUserModal.tsx
import React, {useState, useRef, useEffect} from 'react';
import {callApi, handleProTableRequest} from '@/utils/request'; // 根据你的实际路径调整

import {
    Button,
    Space,
    message,
    Modal,
    Tag,
    Radio,
    Form,
    Tabs,
} from 'antd';
import {
    ProTable,
    ProColumns,
} from '@ant-design/pro-components';
import {
    getUserListByRole,
    addUserRole,
    deleteUserRole,
    deleteUserRoleBatch,
    queryRoleBindCount
} from '@/services/roleUser';
import {UserOutlined} from "@ant-design/icons";

// 定义用户数据类型
type UserItem = {
    userId: number;
    account: string;
    realName: string;
    phone: string;
    roleId: number;
    bindStatus: number;
    bindStatusDesc: string;
};

type SelectUserModalProps = {
    visible: boolean;
    currentRoleId: number;
    currentRoleName?: string;
    onOk: () => void;
    onCancel: () => void;
};

type UserQueryParams = {
    roleId: number;
    bindStatus: number;
    pageNum: number;
    pageSize: number;
    realName?: string;
    account?: string;
    phone?: string;
};

// 绑定统计数据类型
type BindCountData = {
    bindCount: number;
    notBindCount: number;
};

const SelectUserModal: React.FC<SelectUserModalProps> = ({
                                                             visible,
                                                             currentRoleId,
                                                             currentRoleName,
                                                             onOk,
                                                             onCancel,
                                                         }) => {
    const actionRef = useRef<any>(null);
    const [bindStatus, setBindStatus] = useState<number>(1); // 1: 已绑定, 0: 未绑定
    const [selectedUserIds, setSelectedUserIds] = useState<number[]>([]);
    const [bindCountInfo, setBindCountInfo] = useState<BindCountData | null>(null);

    // 获取绑定统计
    const fetchBindCounts = async () => {
        if (currentRoleId) {
            const result = await callApi<BindCountData>(
                () => queryRoleBindCount({roleId: currentRoleId}),
                {errorMsg: '获取绑定统计失败', hideSuccessMsg: true}
            );
            if (result) {
                setBindCountInfo(result);
            }
        }
    };

    // 打开弹窗时获取统计信息
    useEffect(() => {
        if (visible) {
            fetchBindCounts();
        }
    }, [visible, currentRoleId]);

    // 用户列表列定义
    const columns: ProColumns<UserItem>[] = [
        {
            title: '用户账号',
            align: 'center',
            dataIndex: 'account',
            width: 120,
        },
        {
            title: '用户名称',
            align: 'center',
            dataIndex: 'realName',
            width: 120,
        },
        {
            title: '用户电话',
            align: 'center',
            dataIndex: 'phone',
            width: 120,
        },
        {
            title: '绑定状态',
            align: 'center',
            dataIndex: 'bindStatusDesc',
            width: 100,
            search: false,
            render: (_, record) => (
                <Tag color={record.bindStatus === 1 ? 'success' : 'default'}>
                    {record.bindStatusDesc}
                </Tag>
            ),
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            width: 120,
            fixed: 'right',
            render: (_, record) => (
                <Space>
                    {record.bindStatus === 1 ? (
                        <Button
                            type="link"
                            size="small"
                            danger
                            onClick={() => handleUnbind(record)}
                        >
                            解绑
                        </Button>
                    ) : (
                        <Button
                            type="link"
                            size="small"
                            onClick={() => handleBind(record)}
                        >
                            绑定
                        </Button>
                    )}
                </Space>
            ),
        },
    ];

    const handleOk = () => {
        onOk();
        resetState();
    };

    const handleCancel = () => {
        onCancel();
        resetState();
    };

    const resetState = () => {
        setSelectedUserIds([]);
        setBindStatus(1);
    };

    const handleBind = async (record: UserItem) => {
        const result = await callApi(
            () => addUserRole({userId: record.userId, roleId: currentRoleId}),
            {successMsg: '绑定成功', errorMsg: '绑定失败'}
        );
        if (result) {
            if (actionRef.current) {
                await actionRef.current.reload();
            }
            // 更新统计信息
            fetchBindCounts();
        }
    };

    const handleUnbind = async (record: UserItem) => {
        const result = await callApi(
            () => deleteUserRole({userId: record.userId, roleId: currentRoleId}),
            {successMsg: '解绑成功', errorMsg: '解绑失败'}
        );
        if (result) {
            if (actionRef.current) {
                await actionRef.current.reload();
            }
            // 更新统计信息
            fetchBindCounts();
        }
    };

    const handleBatchBind = async () => {
        if (selectedUserIds.length === 0) {
            message.warning('请选择要绑定的用户');
            return;
        }

        const result = await callApi(
            () => {
                const promises = selectedUserIds.map(userId =>
                    addUserRole({userId, roleId: currentRoleId})
                );
                return Promise.all(promises).then(results => ({
                    code: 200,
                    msg: `批量绑定成功 ${selectedUserIds.length} 个用户`
                }));
            },
            {
                successMsg: `批量绑定成功 ${selectedUserIds.length} 个用户`,
                errorMsg: '批量绑定失败'
            }
        );

        if (result) {
            if (actionRef.current) {
                await actionRef.current.reload();
            }
            setSelectedUserIds([]);
            // 更新统计信息
            fetchBindCounts();
        }
    };

    const handleBatchUnbind = async () => {
        if (selectedUserIds.length === 0) {
            message.warning('请选择要解绑的用户');
            return;
        }

        const result = await callApi(
            () => deleteUserRoleBatch({
                userIds: selectedUserIds,
                roleId: currentRoleId
            }),
            {
                successMsg: `批量解绑成功 ${selectedUserIds.length} 个用户`,
                errorMsg: '批量解绑失败'
            }
        );

        if (result) {
            if (actionRef.current) {
                await actionRef.current.reload();
            }
            setSelectedUserIds([]);
            // 更新统计信息
            fetchBindCounts();
        }
    };

    // 切换标签页
    const onTabChange = (key: string) => {
        const newBindStatus = parseInt(key);
        setBindStatus(newBindStatus);
        // 切换标签页时自动刷新表格
        if (actionRef.current) {
            actionRef.current.reload();
        }
    };

    return (
        <Modal
            title={`"${currentRoleName || '当前角色'}" 用户管理`}
            open={visible}
            onOk={handleOk}
            onCancel={handleCancel}
            width={1000}
            bodyStyle={{padding: 0}}
            destroyOnClose
        >
            <Tabs
                defaultActiveKey="1"
                onChange={onTabChange}
                items={[
                    {
                        label: `已绑定 (${bindCountInfo ? bindCountInfo.bindCount : ''})`,
                        key: '1',
                        children: (
                            <ProTable<UserItem, UserQueryParams>
                                actionRef={actionRef}
                                rowKey="userId"
                                search={{
                                    labelWidth: 'auto',
                                    defaultCollapsed: false,
                                }}
                                tableAlertRender={({selectedRowKeys}) => (
                                    selectedRowKeys.length > 0 && (
                                        <Space size={16}>
                                            <span>
                                                已选 {selectedRowKeys.length} 项
                                            </span>
                                            <Button type="link" danger onClick={handleBatchUnbind}>
                                                批量解绑
                                            </Button>
                                        </Space>
                                    )
                                )}
                                request={async (params, sorter, filter) => {
                                    const queryParams: UserQueryParams = {
                                        pageNum: params.current || 1,
                                        pageSize: params.pageSize || 10,
                                        roleId: currentRoleId,
                                        bindStatus: 1, // 已绑定
                                        realName: params.realName,
                                        account: params.account,
                                        phone: params.phone,
                                    };

                                    return handleProTableRequest<UserItem>(
                                        () => getUserListByRole(queryParams),
                                        {errorMsg: '获取已绑定用户列表失败'}
                                    );
                                }}
                                columns={columns}
                                rowSelection={{
                                    onChange: (selectedRowKeys) => {
                                        setSelectedUserIds(selectedRowKeys as number[]);
                                    },
                                    selectedRowKeys: selectedUserIds,
                                }}
                                pagination={{
                                    defaultPageSize: 10,
                                    showSizeChanger: true,
                                    showQuickJumper: true,
                                    pageSizeOptions: ['10', '20', '30', '50'],
                                }}
                            />
                        ),
                    },
                    {
                        label: `未绑定 (${bindCountInfo ? bindCountInfo.notBindCount : ''})`,
                        key: '0',
                        children: (
                            <ProTable<UserItem, UserQueryParams>
                                actionRef={actionRef}
                                rowKey="userId"
                                search={{
                                    labelWidth: 'auto',
                                    defaultCollapsed: false,
                                }}
                                tableAlertRender={({selectedRowKeys}) => (
                                    selectedRowKeys.length > 0 && (
                                        <Space size={16}>
                                            <span>
                                                已选 {selectedRowKeys.length} 项
                                            </span>
                                            <Button type="link" onClick={handleBatchBind}>
                                                批量绑定
                                            </Button>
                                        </Space>
                                    )
                                )}
                                request={async (params, sorter, filter) => {
                                    const queryParams: UserQueryParams = {
                                        pageNum: params.current || 1,
                                        pageSize: params.pageSize || 10,
                                        roleId: currentRoleId,
                                        bindStatus: 0, // 未绑定
                                        realName: params.realName,
                                        account: params.account,
                                        phone: params.phone,
                                    };

                                    return handleProTableRequest<UserItem>(
                                        () => getUserListByRole(queryParams),
                                        {errorMsg: '获取未绑定用户列表失败'}
                                    );
                                }}
                                columns={columns}
                                rowSelection={{
                                    onChange: (selectedRowKeys) => {
                                        setSelectedUserIds(selectedRowKeys as number[]);
                                    },
                                    selectedRowKeys: selectedUserIds,
                                }}
                                pagination={{
                                    defaultPageSize: 10,
                                    showSizeChanger: true,
                                    showQuickJumper: true,
                                    pageSizeOptions: ['10', '20', '30', '50'],
                                }}
                            />
                        ),
                    },
                ]}
            />
        </Modal>
    );
};

export default SelectUserModal;